<template>

<el-card style="width: 800px; max-width: 100%;">
    <template #header>个人信息</template>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="300px"
      class="demo-ruleForm"
    >
      <el-form-item label="修改密码：" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码：" prop="checkPass">
        <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">
          提交
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

    
  </template>
  
  <script setup>
  import { reactive, ref } from 'vue'
  import { useAdminStore } from '../store/adminStore'
  import  { updatePass } from '../api/apiByUser.js'

  const adminStore = useAdminStore()
  const ruleFormRef = ref()
  
  const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value.length < 3 || value.length > 12) {
    callback(new Error('密码长度应在3到12之间'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error('两次输入不同'))
  } else {
    callback()
  }
}
  
  const ruleForm = reactive({
    pass: '',
    checkPass: ''
  })
  
  const rules = reactive({
    pass: [{ validator: validatePass, trigger: 'blur' }],
    checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  })
  
  const resetForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
}

  const submitForm = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      const password = ruleForm.pass
      const admin = adminStore.admin

      // 创建一个新的对象，包含用户名和密码
      const adminInfo = {
        username: admin,
        password: password
      }

      updatePass(adminInfo)
      resetForm()
    } else {
      console.log('验证失败')
      return false
    }
  })
}


  </script>

<style scoped>

</style>